import React, { Component } from 'react'
import styles from './login.module.css'
import { Button, Checkbox, Form, message } from 'antd';
import { FormTextItem } from '@/components/index.js'
import { post } from '@/lib'
import store from '@/store';

export default class login extends Component {
  onFinish = async (formData) => {
    if (formData.remember) { // 如果需要记住电话号码
      localStorage.phone = formData.phone;
    } else {
      localStorage.phone = ''; // 清空
    }
    const data = await post('/login', {
      phone: formData.phone,
      password: formData.password
    });
    if (!data.success) {
      // return alert(data.message);
      return message.error(data.message);
    }
    // 保存个人信息到全局状态
    store.dispatch({
      type: 'setPersonal', // 方法名称
      payload: data.result, // 传过去参数
    });
    // 登录成功，保存localStore的userId表示登录过
    localStorage.userId = data.result.userId;
    // 跳转到主页
    this.props.history.push('/');
  }

  render() {
    return (
      <div className={styles.container}>
        <div className={styles.form}>
          <Form
            name="basic"
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 16,
            }}
            style={{
              maxWidth: 600,
            }}
            initialValues={{ // 初始值
              phone: localStorage.phone || '',
              remember: true,
            }}
            onFinish={this.onFinish}
            autoComplete="off"
          >
            <FormTextItem label="手机号码" name="phone" type="phone" />
            <FormTextItem label="登录密码" name="password" />
            
            <Form.Item
              name="remember"
              valuePropName="checked"
              wrapperCol={{
                offset: 8,
                span: 16,
              }}
            >
              <Checkbox>记住我</Checkbox>
            </Form.Item>

            <Form.Item
              wrapperCol={{
                offset: 8,
                span: 16,
              }}
            >
              <Button type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    )
  }
}
